/*
 * Copyright 2008 the Breachwalls OSS project and the Others.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package com.breachwalls.quasar.datatype.validator;

import org.apache.commons.validator.GenericValidator;

import com.breachwalls.quasar.datatype.Datatype;
import com.breachwalls.quasar.messages.ErrorMessage;
import com.breachwalls.quasar.messages.SimpleErrorMessage;

/**
 * 半角の数値であることをチェックするバリデータ.
 * @author todoken
 * @version $Revision$
 */
public class DigitDatatypeValidator implements DatatypeValidator {

    /**
     * シリアルバージョンID.
     */
    private static final long serialVersionUID = 1L;

    /**
     * デフォルトのエラーメッセージのキー.
     */
    private static final String DEFAULT_MESSAGE_KEY = "errors.digit";

    /**
     * {@inheritDoc}
     */
    public boolean validate(String fieldName, Datatype datatype, ValidatorConfig config) {
        final String value = datatype.toString();

        if (GenericValidator.isLong(value)) {
            String message = DatatypeValidatorUtils.getMessageKey(config, DEFAULT_MESSAGE_KEY);
            String field = DatatypeValidatorUtils.getFieldSuffix(fieldName, FIELD_PREFIX, config);
            Object[] args = new Object[] {field, value };
            ErrorMessage error = new SimpleErrorMessage(fieldName, message, args);
            datatype.addErrorMessage(error);
            return false;
        }

        return true;
    }

}
